package com.yuke.cloud.service.omc.job;

/**
 * 平台向店铺定时结算任务
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSysInfoDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.config.Quartz;
import com.yuke.cloud.service.omc.controller.frontend.PayController;
import com.yuke.cloud.service.omc.controller.frontend.WxPayController;
import com.yuke.cloud.service.omc.dto.OdsCommissionDto;
import com.yuke.cloud.service.omc.dto.OrderShopDto;
import com.yuke.cloud.service.omc.entity.OdsCommission;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsStockGoods;
import com.yuke.cloud.service.omc.entity.OdsStockOrder;
import com.yuke.cloud.service.omc.service.*;
import com.yuke.cloud.service.omc.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Component
@Slf4j
public class orderQuartz {
    private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(orderQuartz.class);

    @Autowired
    private OdsOrderService odsOrderService;
    @Autowired
    private WxPayController wxPayController;
    @Autowired
    private PayController paycontroller;
    @Autowired
    private OdsStockGoodsService odsStockGoodsService;
    @Resource
    private OdsStockOrderService odsStockOrderService;

    @Resource
    private OdsCommissionService odsCommissionService;
    @Resource
    private OdsCommissionOrderService odsCommissionOrderService;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private CmcFeignApi cmcFeignApi;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;
    /**
     * 店铺线上库存预订划拨定时任务
     */
    //@Scheduled(cron = "0 0 2 * * ?")  // 每天凌晨2点进行
    public void transferproduct() {
        List<Map> list = odsStockGoodsService.transfereveryday();
        List<Map> list1 = new ArrayList<>();
        List<Long> listStockGoodsId = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            Map map1 = new HashMap();
            //订单id用来获取店铺id
            OdsStockOrder stock_goods_id = odsStockOrderService.findById(Long.valueOf(map.get("stock_order_id").toString()));
            //规格id数量
            // add by wg 20190327 只有支付的订单才增加库存
            if (stock_goods_id.getPayStatus() == 1) {
                map1.put("shopId", stock_goods_id.getShopId());
                map1.put("specId", Long.valueOf(map.get("spec_id").toString()));
                map1.put("goodsNum", map.get("stock_number"));
                list.add(map1);

                listStockGoodsId.add(Long.valueOf(map.get("stock_goods_id").toString()));
            }
        }
        String s = JSON.toJSONString(list);
        Integer updateCount = 0;
        updateCount = smcFeignApi.updateStockCount(s);

        // add by wg 20190407 修改入库状态
        if (updateCount != null && updateCount > 0) {
            OdsStockGoods odsStockGoods = new OdsStockGoods();
            odsStockGoods.setGoodsStatus((byte)1);
            odsStockGoods.setInboundTime(new Date());
            Example example = new Example(OdsStockGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("stockGoodsId", listStockGoodsId);
            odsStockGoodsService.updateByExample(odsStockGoods, example);

            //todo 可以增加商品划拨通知消息的发送
        }
    }

//    /**
//     * 店铺线上库存预订划拨定时任务
//     */
//    @Scheduled(cron = "0/5 * * * * ?")  // 每天凌晨3点进行
//    public void wmcStorageAdd() {
//        System.out.println("增加库存");
//        List<StorageDto> storageDtos = wmcStorageFeignApi.getStorageInfo();
//        for(StorageDto item : storageDtos){
//            if (item.getNum()<25){
//                item.setNum(item.getNum()+200);
//            }
//
//        }
//        wmcStorageFeignApi.updateStorageNum(storageDtos);
//    }
    /**
     * 对于支付时间超过7天的订单进行更新
     * 主要是已发货、已确认的订单，发货时间过7天的
     */
    @Scheduled(cron = "0 0 1 * * ?")  // 每天晚上1点触发
    public void updateorderstatus() {
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        Date date = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(5, -7);
        Date time7 = instance.getTime();
        Calendar instance1 = Calendar.getInstance();
        instance1.setTime(date);
        instance1.add(5, -8);
        Date time8 = instance1.getTime();
        criteria.andGreaterThanOrEqualTo("sendTime", time8);
        criteria.andLessThanOrEqualTo("sendTime", time7);
        criteria.andEqualTo("orderStatus", 1);//已确认
        criteria.andEqualTo("shippingStatus",2);//已发货
        List<OdsOrder> list = odsOrderService.selectByExample(example);
        System.out.println("检查订单是否完成："+list);
        if (list.size() == 0 ) {
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            list.get(i).setShippingStatus((byte)3); // add by wg 20190708 已收货
            list.get(i).setOrderStatus((byte) 2);
            list.get(i).setAmountPaid( list.get(i).getAmountPayable());
            odsOrderService.update(list.get(i)); // add by wg 20190327
        }

    }

    /**
     * 店铺订单结算定时任务
     * V1.1版后，只有即时达店铺配送及厂家直销商品才有结算任务
     */
    @Scheduled(cron = "0 0 3 * * ?")
    // @Scheduled(fixedRate = 20000)
    public void transfereveryday() throws Exception {
        List<OdsOrder> listfinal = new ArrayList<>();
        List<OdsOrder> list = odsOrderService.transferEveryday(Quartz.day);
        for (OdsOrder odsOrder : list) {
            if (odsOrder.getOrderStatus().toString().equals("4") || odsOrder.getOrderStatus().toString().equals("5")) {
                Integer refundmoney=wmcStorageFeignApi.getrefundamound(odsOrder.getOrderId());
                if(refundmoney==null){
                    log.error("获取订单退货退款信息失败");
                    return;
                }
                //部分退款，需要转账，订单总金额-已退款部分为最终结算的款
                odsOrder.setRefundMoney(refundmoney);
                listfinal.add(odsOrder);
            } else if (odsOrder.getOrderStatus().toString().equals("2")) {
                boolean flag = wmcStorageFeignApi.ifexits(odsOrder.getOrderId());
                if (!flag) {
                    //正常购买，不退款的
                    odsOrder.setRefundMoney(0);
                    listfinal.add(odsOrder);
                }
            }
        }
        List<Long> shopids = new ArrayList<>();
        for (int i = 0; i < listfinal.size(); i++) {
            OdsOrder odsOrder = listfinal.get(i);
            Long shopId = odsOrder.getShopId();
            // add by wg 20190518 如果订单是由厂家直销的，则店铺ID为厂家直销店铺ID
            if (odsOrder.getIsFactory()) {
                shopId = odsOrder.getFactoryShopId();
            }
            // mod by wg 20190518
//            if (shopids.contains(odsOrder)) {
            if (shopids.contains(shopId)) {
            } else {
                shopids.add(shopId);
            }
        }
        List<ShopInfoDto> shopAccountByShopIds = smcFeignApi.getShopAccountByShopIds(shopids);
        if(shopAccountByShopIds==null||shopAccountByShopIds.size()==0){
            System.out.println("获取账户失败");
            return;
        }
        Map map2 = null;
        List<Map<String, Object>> list2 = new ArrayList();
        for (int i = 0; i < shopAccountByShopIds.size(); i++) {
            // add by wg 20190518 对云顶商人及自营店进行过虑
            if (shopAccountByShopIds.get(0).getShopType() == 2 || shopAccountByShopIds.get(0).getShopType() == 4) {
                continue;
            }

            int totalmoney = 0;
            // mod by wg 20190411
//            StringBuilder sb=new StringBuilder();
            JSONArray orderJsonArray = new JSONArray();
            map2 = new HashMap();
            // mod by wg 20190412 应该是可以转账的订单
//            for (int j = 0; j < list.size(); j++) {
            for (int j = 0; j < listfinal.size(); j++) {
                JSONObject orderJson = new JSONObject();
                if (listfinal.get(j).getShopId().toString().equals(shopAccountByShopIds.get(i).getShopId().toString())) {  // mod by wg 20190412 应该是可以转账的订单，list -> listfinal
                    OdsOrder odsOrder = listfinal.get(j); // mod by wg 20190412 应该是可以转账的订单，list -> listfinal
                    Integer amountPaid = odsOrder.getAmountPaid();
                    if (odsOrder.getRefundMoney() != null) {
                        // mod by wg 20190327
//                        totalmoney += amountPaid - odsOrder.getRefundMoney(); // todo 还应减去运费
                        if (odsOrder.getShippingType() == 3) { // 云顶店铺直接发货情况，运费也由店铺所得
                            totalmoney += (amountPaid - odsOrder.getRefundMoney());
                        } else {
                            totalmoney += (amountPaid - odsOrder.getRefundMoney() - odsOrder.getFreightPayable());
                        }
                        // mod by wg 20190411
//                        sb.append(odsOrder.getOrderId()).append(",");
                        orderJson.put("orderId", odsOrder.getOrderId());
                        // mod by wg 20190327
                        if (odsOrder.getShippingType() == 3) { // 云顶店铺直接发货情况，运费也由店铺所得
                            orderJson.put("amountCheckout", amountPaid - odsOrder.getRefundMoney());
                        } else {
                            orderJson.put("amountCheckout", amountPaid - odsOrder.getRefundMoney() - odsOrder.getFreightPayable());
                        }
                        orderJsonArray.add(orderJson);
                    } else {
                        // mod by wg 20190327
//                        totalmoney += amountPaid; // todo 还应减去运费
                        if (odsOrder.getShippingType() == 3) { // 云顶店铺直接发货情况，运费也由店铺所得
                            totalmoney += amountPaid;
                        } else {
                            totalmoney += (amountPaid - odsOrder.getFreightPayable());
                        }
                        // mod by wg 20190411
//                        sb.append(odsOrder.getOrderId()).append(",");
                        orderJson.put("orderId", odsOrder.getOrderId());
                        if (odsOrder.getShippingType() == 3) { // 云顶店铺直接发货情况，运费也由店铺所得
                            orderJson.put("amountCheckout", amountPaid - odsOrder.getFreightPayable());
                        } else {
                            orderJson.put("amountCheckout", amountPaid);
                        }
                        orderJsonArray.add(orderJson);
                    }
                }
            }
            map2.put("account_no", shopAccountByShopIds.get(i).getAccountNo());
            double v = ((double) totalmoney) / 100;
            double value = new BigDecimal(v).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            map2.put("totalmoney",value);
            // mod by wg 20190411
//            map2.put("orderIds",sb.toString());
            map2.put("orderIds",orderJsonArray);
            map2.put("orderType", 1);  // add by wg 20190412 增加订单类型设定，值为用户下单
            map2.put("userId", shopAccountByShopIds.get(i).getUserId());
            list2.add(map2);
        }

        //这个list1就是需要传送过去付款的集合
        System.out.println("开始调用支付宝转账接口，商店账户信息，需要转账金额在list1集合里面");
        //支付失败的，以供后面(支付是否成功)查询，结果以二次查询为准。

        for (Map<String, Object> map : list2) {
            try {
                //支付宝转账，转账成功没有返回，转账失败才返回
                Map transfer = paycontroller.transfer(map);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private List<Map<String, Object>> formatit(List<Map<String, Object>> list) {
        Set set = new HashSet();
        for (int i = 0; i < list.size(); i++) {
            Object shop_id = list.get(i).get("shop_id");
            set.add(shop_id);
        }
        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>(set.size());
        for (Object object : set) {
            Map<String, Object> map = new HashMap<String, Object>();
            Integer totalmoney = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if (object.toString().equals(list.get(i).get("shop_id").toString())) {
                    Map<String, Object> map2 = list.get(i);
                    map.put("shop_id", map2.get("shop_id"));
                    map.put("account_name", map2.get("account_name"));
                    map.put("account_no", map2.get("account_no"));
                    totalmoney += Integer.valueOf(map2.get("money").toString());
                    if (i != list.size() - 1) {
                        sb.append(map2.get("order_id").toString() + ",");
                    } else {
                        sb.append(map2.get("order_id").toString());
                    }
                }
            }
            map.put("totalmoney", totalmoney);
            map.put("all_order_id", sb.toString());
            list1.add(map);
        }
        return list1;
    }





    /*public void findOrderQuartz() {
        System.out.println("进入这里了吗");
        StdSchedulerFactory sf = new StdSchedulerFactory();
        try {
            Scheduler scheduler = sf.getScheduler();
            JobDetail build = JobBuilder.newJob(myJob.class).withIdentity("job1", "job1Group1").build();
            //CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(Quartz.time);
            //CronTrigger build1 = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1").startNow().withSchedule(cronScheduleBuilder).build();
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever()).build();

            // Date date = scheduler.scheduleJob(build, build1);
            Date date = scheduler.scheduleJob(build, trigger);

            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd hh-mm-ss");
            System.out.println(build.getKey() + "   已被安排执行时间:" + sdf.format(date) + "");
            scheduler.start();
            try {
                TimeUnit.MINUTES.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //结束调度
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }*/


    /**
     * 店铺线下订货返利结算
     * todo 目前暂时通过每单结算，而不是月结方式，所以暂时不用，注释掉，20190727
     */
//    @Scheduled(cron = "0 0 4 1 * ?")  // 每月1号凌晨4点执行
    public void shopRebateTask() throws Exception {

        List<Map<String, Object>> listData = odsOrderService.getRebateTransferData();

        if (listData == null || listData.size() <= 0) {
            log.error("获取店铺进货返利数据错误，或没有返利的订单！");
            return;
        }

        for (Map<String, Object> map : listData) {
//            log.info("===============Map={}", map);
            try {
                //支付宝转账，转账成功没有返回，转账失败才犯规
                // 只有金额大于0的才转账
                double totalMoney = (double)map.get("totalmoney");
                if (Double.doubleToLongBits(totalMoney) > Double.doubleToLongBits(0.00)) {
                    Map transfer = paycontroller.transfer(map);
                }
//                log.info("**********transfer={}", transfer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 店铺月累计返利结算
     * todo 月累计金额满9999返0.5%，满19999返1%
     */
    @Scheduled(cron = "0 0 4 8 * ?")   // 每月8号凌晨4点执行
    public void shopRebateMonth() throws Exception {
        //1获得满减活动参数
        //todo 目前只有武汉，当加入其它城市后，这里要取到更多groupId，做循环
        Long groupId =220839532667469824L;
        Map<String,String> map = odsCommissionService.getMonthRebate(groupId);

        //2如果返回为空，或活动未开启，
        if(map == null){
            return;
        }

        double reachFirstMoney = Double.valueOf(map.get("reachFirstMoney"));
        double returnFirstRate =  Double.parseDouble(map.get("returnFirstRate"));
        double reachSecondMoney = Double.valueOf(map.get("reachSecondMoney"));
        double returnSecondRate = Double.parseDouble(map.get("returnSecondRate"));

        //3获取店铺Info
        List<ShopInfoDto> shopInfoDtoList = odsCommissionService.getShopIdsByCondition();
        if (shopInfoDtoList == null || shopInfoDtoList.size() <= 0) {
            log.error("获取店铺信息数据错误！");
            return;
        }
        //4统计店铺已完成订单累计金额
        for(ShopInfoDto item :shopInfoDtoList){

            //如果本月已提交，结束
            Example example = new Example(OdsCommission.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("rebackType", 1);
            criteria.andEqualTo("shopId", item.getShopId());
            criteria.andBetween("createTime",DateUtil.monthTimeBegin(),DateUtil.monthTimeEnd());
            List<OdsCommission> odsCommissions = odsCommissionService.selectByExample(example);
            if (odsCommissions!=null && odsCommissions.size()>0){
                break;
            }

            Date monthBegin = DateUtil.lastMonthTimeBegin();
            Date monthEnd = DateUtil.lastMonthTimeEnd();
            //统计订单优惠前金额20191025
            //List<Map<String,Object>> countSalesByMonth = odsOrderService.countsalesbymonth(monthBegin,monthEnd,item.getShopId());
            //统计订单优惠后实际金额
            List<Map<String,Object>> countSalesByMonth =odsOrderService.countAmountPayableByMonth(monthBegin,monthEnd,item.getShopId());

            if (countSalesByMonth == null || countSalesByMonth.size() <= 0) {
                log.error("获取店铺进货返利数据错误，或没有订单！");
                break;
            }
            Double rebackMoney;
            for (Map<String, Object> countValue : countSalesByMonth) {
            log.info("===============Map={}", map);
                //5计算返利金额
                try {
                    // 只有金额大于0的才转账
                    System.out.println(countValue);
                    Integer totalMoney = Integer.valueOf(countValue.get("SUM(amount_payable)").toString());

                    if (totalMoney >0) {
                        OdsCommission odsCommission = new OdsCommission();
                        odsCommission.setShopName(item.getShopName());
                        odsCommission.setShopId(item.getShopId());
                        odsCommission.setCashType((byte) 4);
                        odsCommission.setRebackType((byte)1);

                        if (Double.doubleToLongBits(totalMoney) >Double.doubleToLongBits(reachSecondMoney)){
                            //6保存返利信息》19999
                           rebackMoney = totalMoney*returnSecondRate;
                            odsCommission.setAmount(Integer.valueOf(  String.valueOf(Math.round(rebackMoney))    ));

                           odsCommissionService.saveCommissionMonthRebate(odsCommission);
                       }else if (Double.doubleToLongBits(totalMoney) >Double.doubleToLongBits(reachFirstMoney)){
                            //6保存返利信息》9999
                           rebackMoney = totalMoney*returnFirstRate;
                            odsCommission.setAmount(Integer.valueOf(  String.valueOf(Math.round(rebackMoney))    ));

                           odsCommissionService.saveCommissionMonthRebate(odsCommission);
                       }
                       return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }//for
        }//for

    }

    /**
     * 店铺发展的会员消费后平台给店铺返利结算
     * 检索8天前的订单
     * todo 每单返10%
     */
    @Scheduled(cron = "0 0 2 * * ?")   // 每天凌晨2点执行
    public void shopcommissionday() throws Exception {
        //1获得返利参数
        //todo 目前只有武汉，当加入其它城市后，这里要取到更多groupId，做循环
        Long groupId =220839532667469824L;
        CmsSysInfoDto cmsSysInfoDto = odsCommissionService.getShopCommissionRebate(groupId);
        System.out.println("获得返利参数:"+cmsSysInfoDto);
        //2如果返回为空，或活动未开启，
        if(cmsSysInfoDto == null || cmsSysInfoDto.getInfoValue() == null || cmsSysInfoDto.getStatus()<1 ){
            return;
        }

        double rate = Double.valueOf(cmsSysInfoDto.getInfoValue());


        //3获取所有已完成的订单
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderStatus", 2);
        //创建完成时间大于8天小于7天
        Date date = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(5, -7);
        Date time7 = instance.getTime();
        Calendar instance1 = Calendar.getInstance();
        instance1.setTime(date);
        instance1.add(5, -8);
        Date time8 = instance1.getTime();
        criteria.andGreaterThanOrEqualTo("sendTime", time8);
        criteria.andLessThanOrEqualTo("sendTime", time7);
        criteria.andEqualTo("shippingStatus",3);//已发货
        criteria.andEqualTo("orderType",1);//C端消费
        criteria.andEqualTo("shopCommissionAmount",0);
        List<OdsOrder> odsOrders = odsOrderService.selectByExample(example);
        System.out.println("获取订单信息数据"+odsOrders);
        if (odsOrders == null || odsOrders.size() <= 0) {
            log.error("获取订单信息数据错误！");
            return;
        }
        //4由订单找用户信息，判断是否是店铺发展的会员
        List<Long> userIds = odsOrders.stream().distinct().map(OdsOrder::getUserId).collect(Collectors.toList());
        System.out.println(userIds);
        Wrapper<List<UserInfoDto>> wrapMapper  = uacUserFeignApi.getUserInfoByUserIds(userIds);
        if (!(wrapMapper.getCode() == 200)){
            log.error("获取用户信息数据错误！");
            return;
        }
        List<UserInfoDto> userInfoDtos = wrapMapper.getResult();

        for(OdsOrder item :odsOrders){
            for (UserInfoDto userInfoDto : userInfoDtos) {
                //判断是否是店铺发展的会员
               if (item.getUserId().equals(userInfoDto.getUserId()) && userInfoDto.getReferenceShopId()>0){
                   //5计算返利金额
                   System.out.println(item.getAmountPayable());
                   Double rebackMoney = item.getAmountPayable()* rate;
                   System.out.println("计算返利金额:"+rebackMoney);
                   try {

                       if (Integer.valueOf(String.valueOf(Math.round(rebackMoney))) >0) {
                           OdsCommissionDto odsCommission = new OdsCommissionDto();
                           odsCommission.setOrderId(item.getOrderId());
                           odsCommission.setShopName(item.getShopName());
                           odsCommission.setShopId(userInfoDto.getReferenceShopId());//发展会员的店铺
                           odsCommission.setCashType((byte) 4);
                           odsCommission.setRebackType((byte)2);
                           odsCommission.setAmount(Integer.valueOf(  String.valueOf(Math.round(rebackMoney))    ));
                           //保存返利信息，保存返利订单信息，通知管理员
                           odsCommissionService.saveShopCommission(odsCommission);

                           //给订单打标记
                            item.setShopCommissionAmount(Integer.valueOf(  String.valueOf(Math.round(rebackMoney))    ));
                            odsOrderService.update(item);

                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
                   break;
               }

            }//for
        }//for
        return;
    }

    /**
     * 定时给业务员发送近三天部分店铺下单情况
     * @throws Exception
     */
    @Scheduled(cron = "0 0 6 * * ?")//每天凌晨6点执行
    public void sendMessage() throws Exception{
        //三天没下单的用户或三天下单金额小于150

        OrderShopDto orderShopDto = new OrderShopDto();
        //得到一个Calendar的实例
        Calendar ca = Calendar.getInstance();
        //设置时间为当前时间
        ca.setTime(new Date());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = df.format(ca.getTime());
        orderShopDto.setEndTime(endTime);
        //日期减3
        ca.add(Calendar.DATE, -3);
        String beginTime = df.format(ca.getTime());
        orderShopDto.setBeginTime(beginTime);
        orderShopDto.setMaxOrder(0);
        List<OrderShopDto> orderInformation = odsOrderService.getOrderInformation(orderShopDto);
        if (orderInformation==null&&orderInformation.size()<0){
            return;
        }
        //String specIds = cmsSpecOrderDto.getGoodsList().stream().map(e -> e.getSpecId().toString()).distinct().collect(Collectors.joining(","));
        String title="近三天没有下单的店铺:";
        String shopName = orderInformation.stream().map(e -> e.getShopName()).distinct().collect(Collectors.joining(","));
        //List<String> shopName = orderInformation.stream().map(e -> e.getShopName()).collect(Collectors.toList());
        String[] split = shopName.split(",");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < split.length&& i<100  ; i++) {
            String s = split[i];
            sb.append(s);
            sb.append(",");
        }
        String s = sb.toString().substring(0,sb.length()-1);
        //获取需要发送通知的人手机号码
        List<Long> list = new ArrayList<>();
        /*list.add(174106725740314624L);
        list.add(262956957802037248L);
        list.add(268485955504177152L);*/
        list.add(291980016852533248L);
        Wrapper<List<UserInfoDto>> userInfoByUserIds = uacUserFeignApi.getUserInfoByUserIds(list);
        if (userInfoByUserIds == null || userInfoByUserIds.getResult() == null || userInfoByUserIds.getResult().size() == 0) {
            throw new UacBizException(ErrorCodeEnum.GL99990002);
        }
        List<UserInfoDto> userList = userInfoByUserIds.getResult();
        //获取手机号码
        List<Long> collect = userList.stream().map(UserInfoDto::getUserId).collect(Collectors.toList());
        MsgNotificationBody msgNotificationBody = new MsgNotificationBody();
        msgNotificationBody.setReceiveType((byte)3);
        msgNotificationBody.setMsgType("shopMsg");
        msgNotificationBody.setTitle(title);
        msgNotificationBody.setContent(s);
        msgNotificationBody.setContent(shopName);
        msgNotificationBody.setTime(new Date());
        if (collect!=null&&collect.size()>0){
            for (Long userId : collect) {
                    opcSendNotifyFeignApi.sendnotify(userId.toString(),title,  JSON.toJSON(msgNotificationBody).toString(), 1);
            }
        }

    }
}
